<?php

/**
 * Created by PhpStorm.
 * User: dumbledore
 * Date: 2018/3/7
 * Time: 下午3:24
 */
class Single_sign_api extends CI_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->load->database();
        $this->load->library('form_validation');//加载表单验证类库
        $this->load->helper('json');
        $this->load->helper('url');
        $this->load->helper('common');
        $this->load->model('user_model');
        $this->load->model('customer_model');
        $this->load->model('admin_model');
        $this->load->library('session');
//        $this->output->set_content_type('charset=utf-8');
    }


    // 商城调用  单点登录
    public function login_api()
    {
        $post = $_GET;
        $callback = isset($_GET['callback']) ? $_GET['callback'] : '';
        unset($post['_']);


        log_message('error', json_encode($post));
        log_message('error', json_encode($_GET));


        if (check_param($post, ['shop_customer_id', 'time_stamp', 'token'])) {
            if (!$callback) {
                $data = ['code' => -1, 'data' => '', 'msg' => '登录失败，callback为空，请使用jsonp'];
                echo $callback . '(' . json_encode($data) . ')';

                log_message('error', 1);
                exit;
            }
            // 生成token，校验
            $token = create_token($post, $this->config->item("token_const"));
            if ($post['token'] != $token) {
                $data = ['code' => -1, 'data' => '', 'msg' => '验签错误'];
                echo $callback . '(' . json_encode($data) . ')';
                log_message('error', 2);
                exit;
            }
            // 校验时间戳是否超时
            $now_time = time();
            $time_out = $this->config->item("time_out");
            $in_time = $now_time - $post['time_stamp'];
            if ($in_time > $time_out) {
                $data = ['code' => -1, 'data' => '', 'msg' => '超时'];
                echo $callback . '(' . json_encode($data) . ')';
                log_message('error', 3);
                exit;
            }

            $shop_customer_id = $post['shop_customer_id'];


            $customer = $this->customer_model->query_shop_customer_info($shop_customer_id);
            if ($customer) {
                log_message('error', 4);
                $this->session->set_userdata('customer_id', $customer['id']);

                // 商城返回过来的shop_customer_id 查询商城具体详情
                $url = $this->config->item("shop_url") . 'companymanagerapi/company_user_info/';
                $data_arr['time'] = time();
                $data_arr['key'] = md5($this->config->item("token_const_wjyh") . $data_arr['time']);
                $data_arr['shop_customer_id'] = $shop_customer_id;
                $rs = curl_request($url, $data_arr);
                $rs = json_decode($rs, true);
                if ($rs['code'] == '200') {
                    $new = array(
                        'username' => $rs['data']['user_name'],
                        'name' => $rs['data']['user_real_name'],
                        'tel' => $rs['data']['user_phone_mob'],
                        'email' => $rs['data']['user_email']
                    );
                    $this->db->where(array("shop_user_id" => $shop_customer_id))->update('app_customer', $new);
                }

                $sql = 'select username,shop_user_id,company,name,identity,status from app_customer WHERE id = ' . $customer['id'];
                $customer_info = $this->db->query($sql)->row_array();
                $this->session->set_userdata('customer_info', $customer_info);
                // 返回给商城
                $data = ['code' => 0, 'data' => '', 'msg' => '登录成功'];
                echo $callback . '(' . json_encode($data) . ')';
                exit;
            } else {
                // 商城返回过来的shop_customer_id 查询赚钱雄器具体详情
                $city_manager_base_url = $this->config->item("city_manager_base_url");
                $api_url = $city_manager_base_url . '/customer/get_customer_info_api';
                $res = curl_request($api_url, ['shop_customer_id' => $shop_customer_id]);
                if ($res) {
                    log_message('error', 5);
                    $res_arr = json_decode($res, true);
                    log_message('error', $res_arr['status']);
                    if ($res_arr['status'] == 'success') {
                        log_message('error', 6);
                        // 保存客户信息
                        log_message('error', json_encode($res_arr['data']));
                        $res = $this->admin_model->save_admin_info_by_shop_customer_id($shop_customer_id, $res_arr['data']);
                        if ($res) {
                            log_message('error', 7);
                            $this->session->set_userdata('customer_id', $res);
                            $sql = 'select username,shop_user_id,company,name,identity,status from app_customer WHERE id = ' . $res;
                            $customer_info = $this->db->query($sql)->row_array();
                            $this->session->set_userdata('customer_info', $customer_info);
                            // 返回给商城
                            $data = ['code' => 0, 'data' => '', 'msg' => '登录成功'];
                            echo $callback . '(' . json_encode($data) . ')';
                            exit;
//                        send_json(array('code'=>0,'data'=>['activation'=>$customer_info['activation']],'msg'=>"登录成功"));
                        } else {
                            log_message('error', 8);
                            // 返回给商城
                            $data = ['code' => -1, 'data' => '', 'msg' => '处理赚钱雄器新客户失败'];
                            echo $callback . '(' . json_encode($data) . ')';
                            exit;
                        }

                    } else {
                        // 商城返回过来的shop_customer_id 查询商城具体详情
                        $url = $this->config->item("shop_url") . 'companymanagerapi/company_user_info/';
                        $data_arr['time'] = time();
                        $data_arr['key'] = md5($this->config->item("token_const_wjyh") . $data_arr['time']);
                        $data_arr['shop_customer_id'] = $shop_customer_id;
                        $rs = curl_request($url, $data_arr);
                        $rs = json_decode($rs, true);

                        $res = $this->admin_model->save_customer_info_by_shop_customer_id($shop_customer_id, $rs['data']);
                        if ($res) {
                            log_message('error', 9);
                            $this->session->set_userdata('customer_id', $res);
                            $sql = 'select username,shop_user_id,company,name,identity,status from app_customer WHERE id = ' . $res;
                            $customer_info = $this->db->query($sql)->row_array();
                            $this->session->set_userdata('customer_info', $customer_info);
                            // 返回给商城
                            $data = ['code' => 0, 'data' => '', 'msg' => '登录成功'];
                            echo $callback . '(' . json_encode($data) . ')';
                            exit;
//                        send_json(array('code'=>0,'data'=>['activation'=>$customer_info['activation']],'msg'=>"登录成功"));
                        } else {
                            log_message('error', 10);
                            // 返回给商城
                            $data = ['code' => -1, 'data' => '', 'msg' => '处理商城新客户失败'];
                            echo $callback . '(' . json_encode($data) . ')';
                            exit;
                        }

                        log_message('error', 11);
                        // 返回给商城
                        $data = ['code' => -1, 'data' => '', 'msg' => '登录失败'];
                        echo $callback . '(' . json_encode($data) . ')';
                        exit;
                    }
                } else {
                    log_message('error', 12);
                    $data = ['code' => -1, 'data' => '', 'msg' => '赚钱雄器接口错误'];
                    echo $callback . '(' . json_encode($data) . ')';
                    exit;
                }
            }
        } else {
            log_message('error', 30);
            // 返回给商城
            $data = ['code' => -1, 'data' => '', 'msg' => '登录失败，参数错误'];
            echo $callback . '(' . json_encode($data) . ')';
            exit;
        }
    }

    // 登出
    public function logout_api()
    {
//        log_message('error', var_export($_GET));
        $callback = $_GET['callback'];
        $post = $_GET;
        unset($post['_']);
        log_message('error', 'logout');
        if (check_param($post, ['time_stamp', 'token'])) {
            if ($this->session->customer_id) {
                log_message('error', 1);
                log_message('error', $this->session->customer_id);
                if (!$callback) {
                    log_message('error', 2);
                    $data = ['code' => -1, 'data' => '', 'msg' => '登录失败，callback为空，请使用jsonp'];
                    echo $callback . '(' . json_encode($data) . ')';
                    exit;
                }
                // 生成token，校验
                $token = create_token($post, $this->config->item("token_const"));
                if ($post['token'] != $token) {
                    log_message('error', 3);
                    $data = ['code' => -1, 'data' => '', 'msg' => '验签错误'];
                    echo $callback . '(' . json_encode($data) . ')';
                    exit;
                }
                // 校验时间戳是否超时
                $now_time = time();
                $time_out = $this->config->item("time_out");
                $in_time = $now_time - $post['time_stamp'];
                if ($in_time > $time_out) {
                    log_message('error', 4);
                    $data = ['code' => -1, 'data' => '', 'msg' => '超时'];
                    echo $callback . '(' . json_encode($data) . ')';
                    exit;
                }

                $this->session->unset_userdata(['customer_id', 'customer_info']);
                // 返回给商城
                $data = ['code' => 0, 'data' => '', 'msg' => '注销成功'];
                echo $callback . '(' . json_encode($data) . ')';
                log_message('error', 100);
                exit;
            } else {
                log_message('error', 8);
                // 返回给商城
                $data = ['code' => -1, 'data' => '', 'msg' => '尚未登录'];
                echo $callback . '(' . json_encode($data) . ')';
                exit;
            }
        } else {
            log_message('error', 9);
            // 返回给商城
            $data = ['code' => -1, 'data' => '', 'msg' => '登录失败，参数错误'];
            echo $callback . '(' . json_encode($data) . ')';
            exit;
        }
    }

}